package com.xingda.packing.plc.service.impl;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.apache.plc4x.java.PlcDriverManager;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
import org.springframework.stereotype.Component;

import com.xingda.packing.config.appset.AppSetPLC;
import com.xingda.packing.plc.service.PlcConnService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class PlcConnServiceImpl implements PlcConnService {

	private static PlcConnection plcConnection;

	@Override
	public PlcConnection getConn() {

		if (plcConnection == null || !plcConnection.isConnected()) {
			alwaysConn();
		}

		return plcConnection;
	}

	private void alwaysConn() {

		String plcUrl = AppSetPLC.plc_url;

		if (Objects.isNull(plcUrl)) {
			log.debug("PLC连接Url为null");
			return;
		}

		while (true) {

			try {
				log.info("连接PLC:{}", plcUrl);
				plcConnection = new PlcDriverManager().getConnection(plcUrl);
				break;

			} catch (PlcConnectionException e) {
				e.printStackTrace();
				try {
					TimeUnit.MILLISECONDS.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}

	}

}
